package fr.cie.blog.controller.interceptors;

import java.util.Map;

import org.apache.log4j.Logger;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.Interceptor;

import fr.cie.blog.beans.User;

/**
 * @author Jee3
 * 
 */
public class RoleInterceptorAdmin extends ActionSupport implements Interceptor {

	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = -3985780404689879408L;

	/**
	 * Log4J the logger.
	 */
	private static final Logger LOG = Logger
			.getLogger(RoleInterceptorAdmin.class);

	/**
	 * LOGIN_ATTEMPT.
	 */
	private static final String LOGIN_ATTEMPT = "loginAttempt";

	@Override
	public final void destroy() {
		LOG.info("Destroy RoleInterceptorAdmin");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#init()
	 */
	@Override
	public final void init() {
		LOG.info("Intializing RoleInterceptorAdmin");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com
	 * .opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public final String intercept(final ActionInvocation invocation)
			throws Exception {

		String message;

		final Map<String, Object> session = ActionContext.getContext()
				.getSession();

		final User pUser = (User) session.get("user");

		// We get the role of the user
		if (pUser == null) {
			// no default user in session => misconfig
			session.put(LOGIN_ATTEMPT, "you've no user => go to index !");
			// result name return
			message = "accessDenied";
			
		} else if (pUser.getRole() < 1) {
			// default user (role == 0)
			session.put(LOGIN_ATTEMPT, "is not admin, is not"
					+ " contributor, you are not connected => register now !");
			message = "accessDenied";

		} else if (pUser.getRole() < 2) {
			// contributor (role == 1)
			session.put(LOGIN_ATTEMPT, "is not admin");
			// result name return
			message = "accessDenied";
		} else {
			// admin (role == 2)
			return invocation.invoke();
		}
		return message;
	}

}